package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApArticleCollectionService;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.article.dto.CollectionBehaviorDto;
import com.heima.model.article.pojo.ApCollection;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author TheCai
 * @date 2021/6/5 14:54
 */
@Service
public class ApArticleCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection>
    implements ApArticleCollectionService {

  @Autowired BehaviorFeign behaviorFeign;

  @Override
  public ResponseResult ApArticleCollection(CollectionBehaviorDto dto) {
    // 1.检验参数
    if (dto.getEntryId() == null || dto.getOperation() == null || dto.getEquipmentId() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    ApUser user = AppThreadLocalUtils.getUser();

    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }

    // 找到实体
    ApBehaviorEntry apBehaviorEntry =
        behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

    if (apBehaviorEntry == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    LambdaQueryWrapper<ApCollection> lambdaQueryWrapper =
        Wrappers.<ApCollection>lambdaQuery()
            .eq(ApCollection::getArticleId, dto.getEntryId())
            .eq(ApCollection::getEntryId, apBehaviorEntry.getId());

    // 找到点赞行为,看看有没有
    if (dto.getOperation().intValue() == 0) {
      ApCollection apCollection = this.getOne(lambdaQueryWrapper);

      if (apCollection != null) {
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "请勿重复收藏");
      }
      ApCollection apCollection1 = new ApCollection();
      apCollection1.setEntryId(apBehaviorEntry.getId());
      apCollection1.setArticleId(dto.getEntryId());
      apCollection1.setType(dto.getType());
      apCollection1.setCollectionTime(new Date());
      apCollection1.setPublishedTime(new Date());
      this.save(apCollection1);

    } else {

      this.remove(lambdaQueryWrapper);
    }

    return ResponseResult.okResult();
  }
}
